package com.cqhz.quwan.ui.main.fragment

import android.content.Intent
import android.graphics.Color
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.blankj.utilcode.util.SizeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.DocumentaryBean
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.PageResultBean
import com.cqhz.quwan.mvp.buy.DocumentaryContract
import com.cqhz.quwan.mvp.buy.DocumentaryPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.activity.ExpertDetailActivity
import com.cqhz.quwan.ui.activity.PlanDetailActivity
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.widget.LoadMoreDoneView
import com.cqhz.quwan.util.CommonAdapterHelper
import com.cqhz.quwan.util.CommonDecoration
import com.cqhz.quwan.util.UmengAnalyticsHelper
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView
import kotlinx.android.synthetic.main.fragment_documentary.*
import me.militch.quickcore.core.HasDaggerInject
import java.util.*
import javax.inject.Inject


/**
 * 首页-跟单页面
 * Created by Guojing on 2018/10/29.
 */
class DocumentaryFragment : AbsFragment(), DocumentaryContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var documentaryPresenter: DocumentaryPresenter
    private var loginBean: LoginBean? = null
    private var titles = arrayOf("按人气", "按命中", "按盈利", "按关注")
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var orders = ArrayList<ArrayList<DocumentaryBean>>()

    companion object {
        fun newInstance() = DocumentaryFragment()
    }

    override fun inject(activityInject: ActivityInject) {
        activityInject.inject(this)
    }

    override fun layout(): Int {
        return R.layout.fragment_documentary
    }

    override fun initView() {
        documentaryPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }

        // 初始化页面元素和相应数据以及适配器
        for (i in 0 until titles.size) {
            initAdapter(i)
        }

        initPager()

        action_goto_rule.setOnClickListener {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "跟单规则")
            val url = "${API.followOrderRule}"
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        // 加载数据
        refreshCurrentPage(0)
    }


    /**
     * 初始化列表适配器
     */
    private fun initAdapter(position: Int) {
        // 当前页面的布局
        var pageView = LayoutInflater.from(context).inflate(R.layout.layout_page_swipe, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(context).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var orderList = ArrayList<DocumentaryBean>()
        var orderListAdapter = CommonAdapterHelper.getDocumentaryOrderListAdapter(this!!.activity!!, orderList, position)
        orderListAdapter.emptyView = emptyView
        orderListAdapter.setLoadMoreView(LoadMoreDoneView())

        // 当前页面列表适配器的事件
        holder.rvContent.layoutManager = LinearLayoutManager(context)
        holder.rvContent.addItemDecoration(CommonDecoration(16))
        if (position == 3) {
            holder.rvContent.setSwipeMenuCreator(menuCreator)
            // 这个方法要放到setAdapter之前
            holder.rvContent.setSwipeMenuItemClickListener { menuBridge ->
                menuBridge.closeMenu()
                val position = menuBridge.adapterPosition
                var currentPage = vp_content.currentItem
                val item = orders[currentPage][position] as DocumentaryBean
                documentaryPresenter.updateFollowStatus(item!!.userId!!, loginBean!!.userId!!, "0")// 取消关注
            }
        }
        holder.rvContent.adapter = orderListAdapter
        orderListAdapter.setOnLoadMoreListener({
            var currentPage = vp_content.currentItem
            if (orders[currentPage].size > 0) {
                if (orders[currentPage].size % KeyContract.pageSize == 0) {
                    var pageNo = orders[currentPage].size / KeyContract.pageSize + 1
                    holders[currentPage].refreshLayout.isEnableRefresh = false
                    documentaryPresenter.getOrderList(pageNo, KeyContract.pageSize, currentPage, loginBean!!.userId!!)
                } else {
                    adapters[currentPage].loadMoreEnd()
                    documentaryPresenter.getOrderList(1, KeyContract.pageSize, currentPage, loginBean!!.userId!!)
                }
            } else {
                holders[currentPage].refreshLayout.isEnableRefresh = false
            }
        }, holder.rvContent)
        orderListAdapter.onItemClickListener = object : OnItemClickListener(), BaseQuickAdapter.OnItemClickListener {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var currentPage = vp_content.currentItem
                val item = adapters[currentPage].getItem(position) as DocumentaryBean
                if (currentPage == 3) {
                    gotoExpertDetail(item)
                } else {
                    gotoPlanDetail(item)
                }
            }
        }
        orderListAdapter.setOnItemChildClickListener { adapter, view, position ->
            var currentPage = vp_content.currentItem
            val item = adapters[currentPage].getItem(position) as DocumentaryBean
            when (view.id) {
                R.id.civ_avatar, R.id.tv_name, R.id.tv_desc -> gotoExpertDetail(item)
                R.id.action_follow_buy -> gotoPlanDetail(item)
            }
        }

        // 刷新
        holder.refreshLayout.setOnRefreshListener {
            var currentPage = vp_content.currentItem
            refreshCurrentPage(currentPage)
        }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        orders.add(orderList)
        adapters.add(orderListAdapter)
    }

    /**
     * 跳转到专家详情
     */
    private fun gotoExpertDetail(item: DocumentaryBean) {
        if (APP.get()!!.loginInfo == null) {
            startActivity(Intent(context, LoginActivity::class.java))
            return
        }

        val intent = Intent(context(), ExpertDetailActivity::class.java)
        intent.putExtra(KeyContract.UserId, item.userId)
        startActivity(intent)
    }

    /**
     * 跳转到方案详情
     */
    private fun gotoPlanDetail(item: DocumentaryBean) {
        if (APP.get()!!.loginInfo == null) {
            startActivity(Intent(context, LoginActivity::class.java))
            return
        }

        val intent = Intent(context(), PlanDetailActivity::class.java)
        intent.putExtra(KeyContract.OrderId, item.orderId)
        intent.putExtra(KeyContract.ExpertId, item.userId)
        startActivity(intent)
    }

    /**
     * 构建侧滑菜单
     */
    private var menuCreator: SwipeMenuCreator = SwipeMenuCreator { swipeLeftMenu, swipeRightMenu, viewType ->
        /**
         * Create menu for recyclerVie item.
         *
         * @param swipeLeftMenu  The menu on the left.
         * @param swipeRightMenu The menu on the right.
         * @param viewType       The view type of the new view.
         */
        // create "open" item
        val deleteItem = SwipeMenuItem(context)
        deleteItem.height = ViewGroup.LayoutParams.MATCH_PARENT
        deleteItem.width = SizeUtils.dp2px(70f)
        deleteItem.setBackground(R.color.colorAccent)
        deleteItem.text = "取消关注"
        deleteItem.setTextColor(Color.parseColor("#ffffff"))
        deleteItem.textSize = SizeUtils.sp2px(5f)

        swipeRightMenu.addMenuItem(deleteItem)
    }

    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (orders[position].size <= 0) {
                    refreshCurrentPage(position)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage(currentPage: Int) {
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }
        if (currentPage == 3 && loginBean == null) {
            startActivity(Intent(context, LoginActivity::class.java))
            return
        }
        documentaryPresenter.getOrderList(1, KeyContract.pageSize, currentPage, if (loginBean != null) loginBean!!.userId!! else "")
    }

    override fun loadOrderList(currentPage: Int, pageNo: Int, pageResultBean: PageResultBean<DocumentaryBean>) {
        if (pageNo == 1) {
            orders[currentPage].clear()
            adapters[currentPage].setEnableLoadMore(true)
            if (holders[currentPage].refreshLayout.state.isHeader) {
                holders[currentPage].refreshLayout.finishRefresh()
            }
        }

        if (pageResultBean.records.isNotEmpty()) {
            orders[currentPage].addAll(pageResultBean.records)
        }

        if (pageResultBean.total > orders[currentPage].size) {
            adapters[currentPage].loadMoreComplete()
        } else {
            adapters[currentPage].loadMoreEnd()
        }

        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    override fun updateSuccess() {
        var currentPage = vp_content.currentItem
        refreshCurrentPage(currentPage)
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as SwipeMenuRecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onResume() {
        super.onResume()
        UmengAnalyticsHelper.onPageStart("直播")// 统计页面
        UmengAnalyticsHelper.onResume(context())

        var currentPage = vp_content.currentItem
        loginBean = if (APP.get()!!.loginInfo != null) {
            APP.get()!!.loginInfo
        } else {
            null
        }
        if (currentPage == 3 && loginBean == null) {
            return
        }
        documentaryPresenter.getOrderList(1, KeyContract.pageSize, currentPage, if (loginBean != null) loginBean!!.userId!! else "")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!isHidden) {
            this.onResume()
        } else {
            this.onPause()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        documentaryPresenter.detachView()
    }

    override fun onPause() {
        super.onPause()
        UmengAnalyticsHelper.onPageEnd("直播")// 统计页面
        UmengAnalyticsHelper.onPause(context())
    }
}